const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * 格式化时间显示
 * 1-59分钟内: 显示分钟数
 * 1-23小时内: 显示小时数
 * 1-30天内: 显示天数
 * 超过30天: 显示完整日期时间
 * @param {Date|string} dateStr 日期字符串或Date对象
 * @returns {string} 格式化后的时间字符串
 */
const formatTimeAgo = (dateStr) => {
  if (!dateStr) return '';
  
  let date;
  if (typeof dateStr === 'string') {
    // 尝试将字符串转换为日期对象
    date = new Date(dateStr.replace(/-/g, '/'));
    if (isNaN(date.getTime())) return dateStr; // 如果转换失败，返回原字符串
  } else if (dateStr instanceof Date) {
    date = dateStr;
  } else {
    return dateStr + ''; // 如果不是Date对象或字符串，转为字符串返回
  }
  
  const now = new Date();
  const diffMilliseconds = now - date;
  const diffMinutes = Math.floor(diffMilliseconds / (1000 * 60));
  const diffHours = Math.floor(diffMilliseconds / (1000 * 60 * 60));
  const diffDays = Math.floor(diffMilliseconds / (1000 * 60 * 60 * 24));
  
  if (diffMinutes < 60) {
    return diffMinutes <= 0 ? '刚刚' : `${diffMinutes}分钟前`;
  } else if (diffHours < 24) {
    return `${diffHours}小时前`;
  } else if (diffDays <= 30) {
    return `${diffDays}天前`;
  } else {
    // 超过30天显示完整日期时间
    return formatTime(date);
  }
}

module.exports = {
  formatTime,
  formatTimeAgo
}
